import router from '@/router'
import store from '@/store'
import { NATIVE_TYPE } from '@/type'

class JsBridge {
  public _windows: any = window
  constructor() {
    //
  }
  //login loginOut 登录 或 登出 传用户id给app
  //clearCache 清除缓存
  //versions updateVersions app版本号
  //startCollectPoint endCollectPoint 开始采集经纬度 结束采集经纬度(参数:{token,orderId:订单号,plateNo:车牌号})
  //faceIdentification 人脸认证
  //getCurrentPosition 获取当前定位{longitude:'经度' ，latitude:'纬度'}
  jsCallNative(type: NATIVE_TYPE, info: any) {
    console.log(type, 'type')
    const userAgent = navigator.userAgent
    if (userAgent.indexOf('_Web') != -1) {
      const isAndroid = userAgent.indexOf('Android') > -1 || userAgent.indexOf('Linux') > -1 //安卓
      const isIOS = !!userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) //ios终端
      if (isAndroid) {
        this._windows.suiniyCarrier.getInfoFromJs(type, JSON.stringify(info))
      }
      if (isIOS) {
        if (this._windows.webkit) {
          this._windows.webkit.messageHandlers.getInfoFromJs.postMessage({ type, info: JSON.stringify(info) })
        }
      }
    }
  }

  //获取app传入数据 消息推送  app版本号
  //faceIdentification 人脸认证回调
  nativeCallJs() {
    this._windows.sendInfoToJs = (
      type: 'newsPush' | 'versions' | 'faceIdentification' | 'getCurrentPosition',
      info: string
    ) => {
      // 消息类型 1系统消息, 2运单消息, 3客服消息, 4活动消息
      const newPush = () => {
        const infoObj: any = JSON.parse(info.replace('"{', '{').replace('}"', '}')) ?? {}
        if (infoObj.noticeType === '1') {
          router.push({
            name: 'NewsCenterSystem'
          })
        } else if (infoObj.noticeType === '2') {
          router.push({
            name: 'NewsCenterWaybill'
          })
        } else if (infoObj.noticeType === '4') {
          router.push({
            name: 'NewsCenterActivity'
          })
        }
      }
      const faceIdentification = () => {
        const infoObj: any = JSON.parse(info)
        if (infoObj.message === 'fail') {
          router.push({
            name: 'ValiPayPassword'
          })
        } else {
          router.push({
            name: 'EditPayPassword'
          })
        }
      }

      switch (type) {
        case 'newsPush':
          newPush()
          break
        case 'versions':
          store.commit('system/setCurrentVersions', info)
          break
        case 'getCurrentPosition':
          store.commit('system/setCurrentPosition', info)
          break
        case 'faceIdentification':
          faceIdentification()
          break

        default:
          break
      }
    }
  }
}

export default new JsBridge()
